/**
 * 
 */
package com.etc.controller.login;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.etc.annotation.LogLogin;
import com.etc.common.enums.LoginTypeEnum;
import com.etc.common.enums.UserTypeEnum;
import com.etc.common.util.StringUtil;
import com.etc.constants.WebConstants;
import com.etc.user.model.User;

/**
 * @author Administrator
 *
 */
@Controller
public class LoginController {
	@RequestMapping("/login.htm")
	public String forward() {
		return "login";
	}

	/**
	 * 判断用户是否登录
	 * 
	 * @param currUser
	 * @return
	 */
	@LogLogin(userType = UserTypeEnum.BACKGROUND_USER, loginType = LoginTypeEnum.LOGIN)
	@RequestMapping(value = "/login.jsop", method = RequestMethod.POST)
	public String isLogin(User cmsUser, HttpServletRequest request) {
		Subject user = SecurityUtils.getSubject();
		String remeberMe = request.getParameter("remeberMe");
		UsernamePasswordToken token = new UsernamePasswordToken(cmsUser.getTsuName(),
				cmsUser.getTsuPassword());
		if (StringUtil.isNotEmpty(remeberMe)) {
			token.setRememberMe(Boolean.valueOf(remeberMe));
		}
		try {
			user.login(token);
			request.getSession().setAttribute(cmsUser.getTsuName(), cmsUser);
			request.getSession().setAttribute(WebConstants.USER_KEY, cmsUser);
			return "redirect:/main/index.htm";
		} catch (AuthenticationException e) {
			token.clear();
			return "redirect:/error.htm";
		}
	}

	@RequestMapping(value = "/error.htm")
	public String forwardError() {
		return "error";
	}
	
	@LogLogin(userType = UserTypeEnum.BACKGROUND_USER, loginType = LoginTypeEnum.EXIT)
	@RequestMapping(value = "/logout.jsop")
	@ResponseBody
	public String forwardLogout() {
		SecurityUtils.getSubject().logout();
		return "success";
	}

	
	@RequestMapping(value = "/logout.htm")
	public String forwardLogoutPage() {
		return "logoutSuccess";
	}
}
